from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
import os
import uuid
from datetime import datetime
from api.utils.response import success_response, error_response

@csrf_exempt
def upload_image(request):
    """
    上传图片接口
    支持格式：jpg, jpeg, png, gif
    文件大小限制：5MB
    """
    if request.method == 'POST':
        try:
            # 检查是否有文件
            if 'image' not in request.FILES:
                return error_response(message='没有找到图片文件',code=400)

            image_file = request.FILES['image']
            
            # 检查文件类型
            allowed_types = ['image/jpeg', 'image/png', 'image/gif']
            if image_file.content_type not in allowed_types:
                return error_response(message='不支持的文件类型，仅支持jpg、png、gif格式',code=400)

            # 检查文件大小（5MB）
            if image_file.size > 5 * 1024 * 1024:
                return error_response(message='文件大小超过限制（5MB）',code=400)

            # 生成文件名
            ext = os.path.splitext(image_file.name)[1]
            filename = f"{uuid.uuid4()}{ext}"
            
            # 按年月组织目录
            today = datetime.now()
            relative_path = f"images/{today.year}/{today.month:02d}"
            upload_path = os.path.join(settings.MEDIA_ROOT, relative_path)
            
            # 创建目录
            os.makedirs(upload_path, exist_ok=True)
            
            # 保存文件
            file_path = os.path.join(upload_path, filename)
            with open(file_path, 'wb+') as destination:
                for chunk in image_file.chunks():
                    destination.write(chunk)
            
            # 返回文件URL
            file_url = f"{settings.MEDIA_URL}{relative_path}/{filename}"
            
            return success_response(
                message='上传成功',
                data={
                    'url': file_url,
                    'filename': filename,
                    'size': image_file.size,
                    'content_type': image_file.content_type
                }
            )

        except Exception as e:
            return error_response(message=f'上传失败：{str(e)}',code=500)
    else:
        return error_response(message='仅支持POST请求',code=405) 